﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Akka.Actor;

namespace Dapper.Sharding.CAP
{
    internal class ClientActor : ReceiveActor
    {
        private ClientCap ClientCap { get; }

        public ClientActor(ClientCap clientCap)
        {
            ClientCap = clientCap;

            Receive<CommitMessage>(msg =>
            {
                Sender.Tell(true);
                var ok = ClientCap.dict.TryGetValue(msg.TranId, out var tran);
                if (ok)
                {
                    tran.TranMsg.ClientStatus = msg.Commit ? 1 : -1;
                    try
                    {
                        tran.autoResetEvent.Set();
                    }
                    catch { }
                }
            });

            Receive<CommitTellMessage>(msg =>
            {
                var ok = ClientCap.dict.TryGetValue(msg.TranId, out var tran);
                if (ok)
                {
                    tran.TranMsg.ClientStatus = msg.Commit ? 1 : -1;
                    try
                    {
                        tran.autoResetEvent.Set();
                    }
                    catch { }
                }
            });
        }
    }
}
